package com.atyang.utils;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
public class RedisUtil {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 加锁
     * @param prefix
     * @param key
     * @param expire
     * @return
     */
    public boolean setNx(String prefix, String key, long expire){
        ValueOperations<String, Object> valueOperations = redisTemplate.opsForValue();
        Boolean flag = valueOperations.setIfAbsent(prefix + key, System.currentTimeMillis());
        // 成功之后设置过期时间, 防止超时
        if (flag){
            valueOperations.set(prefix + key, getLongValue(prefix,key), expire, TimeUnit.SECONDS);
        }
        return flag;
    }

    /**
     * 删除锁
     * @param prefix
     * @param key
     */
    public void delete(String prefix, String key){
        redisTemplate.delete(prefix + key);
    }

    /**
     * 获取存锁时的时间
     * @param prefix
     * @param key
     * @return
     */
    public long getLongValue(String prefix, String key){
        return (Long) redisTemplate.opsForValue().get(prefix + key);
    }

}
